//
//  MVVMController.swift
//  HHSwift
//
//  Created by 华宏 on 2019/1/23.
//  Copyright © 2019年 huahong. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
import HandyJSON


class MVVMController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource {
   
    let reuseIdentifier = "MVVMCell"
    private var jsonModel : Model?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "MVVM"
        
        
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        requestData()
       
        
        
        
    }
    
    //MARK:代理方法
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return self.jsonData?["subjects"].array?.count ?? 0;
        return self.jsonModel?.subjects?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell:MVVMCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MVVMCell
        
        //HandyJSON转Model
//        let HandyJSONModel = Model.deserialize(from: self.jsonData?["subjects"][indexPath.item].dictionaryObject)
//        let imageStr :String = HandyJSONModel?.images["large"] as! String
////        let title = HandyJSONModel?.title ?? ""
        let subjects = self.jsonModel?.subjects?[indexPath.item]
        let imageStr :String = subjects?.images?.large ?? ""
        let title = subjects?.title
        
        //SwiftyJSON转Model
//        let model = MVVMModel(jsonData: self.jsonData?["subjects"][indexPath.item] ?? "")
////        let imageStr :String = model.images.large ?? ""
//        let title = model.title
        
        
        let url = URL(string: imageStr)
        cell.imageView.kf.indicatorType = .activity
        cell.imageView.kf.setImage(with: url)
        cell.titleLabel.text = title
       
        //SwiftyJSON
//        let imageStr = self.jsonData?["subjects"][indexPath.item]["images"]["large"].string ?? ""
//        cell.titleLabel.text = self.jsonData?["subjects"][indexPath.item]["title"].string


        return cell
    }
    
    //MARK:懒加载
    lazy var collectionView:UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 100, height: 120)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
       let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MVVMCell.classForCoder(), forCellWithReuseIdentifier: reuseIdentifier)
        
        return collectionView
    }()
    
    //MARK:网络请求
    func requestData() {
        
        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        hud.show(animated: true)
        
        let urlStr = "https://api.douban.com/v2/movie/in_theaters?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&start=0&count=100&client=&udid="
        
        Alamofire.request(urlStr).responseJSON { (response) in

            MBProgressHUD.hide(for: self.view, animated: true)

            switch response.result{
                case .success(let json):
                    
                let dict = json as? [String:Any]
                
                print(dict ?? "")
                
                if let title = dict?["title"]{
                    self.title = title as? String
                }
                
                self.jsonModel = Model.deserialize(from: dict)
                self.collectionView.reloadData()
                
            case .failure(let error):
                print("\(error)")
            }
            
        }
        
    }

}
